﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Eflong.KJFiles;
using Eflong.MonitoringLib.MonitoringUnit;

namespace Eflong.ShenHuaFiles
{
    public class EflongToShenHuaFiles
    {
        private EflongToShenHuaFiles( )
        {
        }

        private static EflongToShenHuaFiles _intance = null;

        /// <summary>
        /// 获取Eflong和神华文件转换的实例
        /// </summary>
        /// <returns></returns>
        public static EflongToShenHuaFiles Instance( )
        {
            if ( _intance == null )
            {
                _intance = new EflongToShenHuaFiles( );
            }
            return _intance;
        }

        /// <summary>
        /// Eflong 的 CoalMineUnit 与 ShenHua_Files 的对应字典
        /// </summary>
        private Dictionary<BaseCoalMineUnit , ShenHua_Files> dic_CoalMineUnitToShenHua_Files = new Dictionary<BaseCoalMineUnit , ShenHua_Files>( );

        /// <summary>
        /// 加入一个矿的基本信息，并关联到一个神华的文件信息
        /// </summary>
        /// <param name="coalMineUnit"></param>
        /// <returns></returns>
        public ShenHua_Files GetCoalMineUnitToShenHua_Files( BaseCoalMineUnit coalMineUnit )
        {
            ShenHua_Files sh_Files;
            if ( !dic_CoalMineUnitToShenHua_Files.ContainsKey( coalMineUnit ) )
            {
                sh_Files = new ShenHua_Files( );
                sh_Files.coalMineUnit = coalMineUnit;
                sh_Files.dev.datetime = DateTime.Now;
                dic_CoalMineUnitToShenHua_Files.Add( coalMineUnit , sh_Files );
            }
            else
            {
                sh_Files = dic_CoalMineUnitToShenHua_Files[ coalMineUnit ];
                sh_Files.coalMineUnit = coalMineUnit;
            }
            return sh_Files;
        }

        /// <summary>
        /// 删除一个矿的信息，并解除与神华的文件信息
        /// </summary>
        /// <param name="coalMineUnit"></param>
        public void DeleteCoalMineUnitToShenHua_Files( BaseCoalMineUnit coalMineUnit )
        {
            if ( dic_CoalMineUnitToShenHua_Files.ContainsKey( coalMineUnit ) )
            {
                ShenHua_Files sh_Files = dic_CoalMineUnitToShenHua_Files[ coalMineUnit ];
                sh_Files.Cleanup( );
                dic_CoalMineUnitToShenHua_Files.Remove( coalMineUnit );
                sh_Files = null;
            }
        }

        /// <summary>
        /// 更新测点定义文件
        /// </summary>
        /// <param name="coalMineUnit"></param>
        public void UpdateDefinitionToShenHua_Files( BaseCoalMineUnit coalMineUnit )
        {
            ShenHua_Files sh_Files = GetCoalMineUnitToShenHua_Files( coalMineUnit );
            sh_Files.dev.datetime = DateTime.Now;
            sh_Files.rtm.head.modify = "1";
            UpdateDefinitionToShenHua_Files( coalMineUnit , ref sh_Files );
            KJXX_Files.WriteFileContent( GetCoalMinePath( coalMineUnit ) + @"\" + sh_Files.dev.getFileName( ) , sh_Files.dev.toString( ) );
        }

        private void UpdateDefinitionToShenHua_Files( BaseCoalMineUnit coalMineUnit , ref ShenHua_Files sh_Files )
        {
            List<BaseMonitoringUnit> units = coalMineUnit.GetMonitoringUnits( );
            for ( int n = 0; n < units.Count; n++ )
            {
                BaseMonitoringUnit unit = units[ n ];
                string sensorNO = GetSensorNO( unit );
                AJDEVItem item = sh_Files.dev.getAJDEVItem( sensorNO );
                SetAJDEVItemFromMonitoringUnit( unit , sensorNO , item );

                // 调校时间
                if ( item.Time == null )
                {
                    item.Time = sh_Files.dev.datetime.ToString( "yyyy-MM-dd HH:mm:ss" , DateTimeFormatInfo.InvariantInfo );
                }

                sh_Files.dev.Add( item );
            }
        }

        /// <summary>
        /// 设置神华的联网测点信息
        /// </summary>
        /// <param name="unit"></param>
        /// <param name="sensorNO"></param>
        /// <param name="item"></param>
        public static void SetAJDEVItemFromMonitoringUnit( BaseMonitoringUnit unit , string sensorNO , AJDEVItem item )
        {
            item.SensorNO = sensorNO;
            item.SersorName = item.GetSensorName( unit.m_Type.ToString( ) , unit.m_strUnit );

            item.Location = unit.m_strName;
            item.AreaName = "其它";

            if ( item.AreaType == null )
            {
                item.AreaType = ( ( int )AreaTypes.其它 ).ToString( );
            }
            if ( item.AreaCode == null )
            {
                item.AreaCode = "T" + ( ( int )AreaCodes.其它 ).ToString( );
            }

            if ( unit.m_Modality != MonitoringUnitModality.Modalities.Digital )
            {
                item.MeteLowValue = string.Format( "{0:f2}" , unit.m_fLowerBound );
                item.MeteUpperValue = string.Format( "{0:f2}" , unit.m_fUpperBound );
                item.AlertLowLimit = string.Format( "{0:f2}" , unit.m_fLowerLimit );
                item.AlertUpperLimit = string.Format( "{0:f2}" , unit.m_fUpperLimit );

                if ( unit.m_Type == MonitoringUnitType.Types.瓦斯 )
                {
                    item.SwitchOnValue = string.Format( "{0:f2}" , unit.m_fRestLimit );
                    item.SwitchOffValue = string.Format( "{0:f2}" , unit.m_fBreakLimit );

                    // 传感器1-5的关联传感器为d1-1;k1-3;b1-4
                    item.LinkageNO = string.Empty;
                    if ( unit.DDSensorID != null )
                    {
                        item.LinkageNO += "d" + GetSensorNO( unit.DDSensorID ) + ";";
                    }
                    if ( unit.KDSensorID != null )
                    {
                        item.LinkageNO += "k" + GetSensorNO( unit.KDSensorID ) + ";";
                    }
                    if ( unit.BSSensorID != null )
                    {
                        item.LinkageNO += "b" + GetSensorNO( unit.BSSensorID ) + ";";
                    }
                }
                else
                {
                    item.SwitchOnValue = "0";
                    item.SwitchOffValue = "0";
                }
            }
            else
            {
                item.SersorUnit = string.Empty;
            }
        }

        /// <summary>
        /// 更新实时数据文件
        /// </summary>
        /// <param name="coalMineUnit"></param>
        public void UpdateDataToShenHua_Files( BaseCoalMineUnit coalMineUnit )
        {
            ShenHua_Files sh_Files = GetCoalMineUnitToShenHua_Files( coalMineUnit );
            sh_Files.rtm.time = DateTime.Now;
            UpdateDataToShenHua_Files( coalMineUnit , ref sh_Files );
            KJXX_Files.WriteFileContent( GetCoalMinePath( coalMineUnit ) + @"\" + sh_Files.rtm.getFileName( ) , sh_Files.rtm.toString( ) );
            sh_Files.rtm.head.modify = "0";
        }

        public static void UpdateDataToShenHua_Files( BaseCoalMineUnit coalMineUnit , ref ShenHua_Files sh_Files )
        {
            List<BaseMonitoringUnit> units = coalMineUnit.GetMonitoringUnits( );
            for ( int n = 0; n < units.Count; n++ )
            {
                BaseMonitoringUnit unit = units[ n ];
                string sensorNO = GetSensorNO( unit );
                AJRTMItem item = sh_Files.rtm.getItem( sensorNO );
                item.SensorNO = sensorNO;
                int state = 0;
                if ( unit.m_Modality != MonitoringUnitModality.Modalities.Digital )
                {
                    MonitoringUnitState.ChineseStates s = ( MonitoringUnitState.ChineseStates )unit.m_State;
                    state = ( int )AJRTMItem.GetAnalogState( s.ToString( ) );
                    item.Value = string.Format( "{0:f2}" , unit.m_fValue );
                }
                else
                {
                    if ( unit.m_State > MonitoringUnitState.States.State2 )
                    {
                        state = ( int )AJDigitalStates.中断;
                    }
                    else
                    {
                        // 正常状态

                        if ( unit.m_State == MonitoringUnitState.States.State0 )
                        {
                            state = ( int )AJDigitalStates.正常; // 正常为 1
                        }
                        else  // 异常状态
                        {
                            state = ( int )AJDigitalStates.异常; // 异常为 0
                        }
                    }

                    item.Value = state.ToString( );
                }
                item.State = state.ToString( );
                sh_Files.rtm.Add( item );
            }
        }

        public static string GetSensorNO( BaseMonitoringUnit unit )
        {
            string sNO = unit.m_strId;
            if ( sNO.Length <= 2 )
            {
                return "0-" + sNO;
            }
            else
            {
                return sNO.Substring( 0 , 2 ) + "-" + sNO.Substring( 2 );
            }
        }

        public static string GetSensorNO( string sNO )
        {
            if ( sNO.Length <= 2 )
            {
                return "0-" + sNO;
            }
            else
            {
                return sNO.Substring( 0 , 2 ) + "-" + sNO.Substring( 2 );
            }
        }

        public static string GetCoalMinePath( BaseCoalMineUnit coalMineUnit )
        {
            // 路径：C:\KJ，每个矿井生成一个文件夹，矿井文件夹的名称格式为：矿名称_矿编号
            string sPath = @"C:\KJ\" + coalMineUnit.m_strName + "_102" + ( coalMineUnit.m_nId + 100 ).ToString( ).Substring( 1 );
            if ( !Directory.Exists( sPath ) )
            {
                Directory.CreateDirectory( sPath );
            }
            return sPath;
        }
    }
}